<?php

namespace App\Models\Clickhouse\KfOrder;


use App\Models\Clickhouse\BaseCHModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageMappingModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageModel;
use App\Models\Shop\ShopModel;
use App\Service\Kms\Home\HomeService;
use App\Service\Kms\Task\UserRoleService;
use Kuafu\LaravelClickHouse\Database\Eloquent\Builder;

class KfOrderCHModel extends BaseCHModel
{
    protected $connection = 'clickhouseOrderData';

    protected $table = "kf_order";

    /**
     * @param int $role
     * @param int $regionSelectionType
     * @param string $region
     * @param string $regionValue
     * @return Builder
     */
    public static function buildHomeSearchQuery(
        int $role,
        int $regionSelectionType,
        string $region,
        string $regionValue
    ): Builder {
        $query = function ($query) {
            return $query->where("shopId", 0);
        };
        if ($role == UserRoleService::ROLE_BASE_SUPERVISOR) {
            $signOrder = OpenShopSignOrderModel::query()->whereHas("checkAcceptRel", function ($query) {
                $query->where("managerId", auth()->user()->rmsUserId);
            })->get();
            if ($signOrder->isNotEmpty()) {
                $shopIds = ShopModel::query()
                                    ->whereIn("shopCode", $signOrder->pluck("shopCode")->toArray())
                                    ->pluck("id")
                                    ->toArray();
                if ($shopIds) {
                    $query = function ($query) use ($shopIds) {
                        $query->whereIn("shopId", $shopIds);
                    };
                }
            }
        } else {
            switch ($regionSelectionType) {
                case HomeService::REGION_SELECTION_TYPE_1:
                    $regionRel = attributeGet(
                        OpenShopOrganizationManageModel::allOrganizationManage()->where("name", $region)->first(),
                        "regionRel",
                        collect([])
                    );
                    if (!empty($regionRel->pluck("provinceCode")->toArray())) {
                        $shopIds = ShopModel::query()
                                            ->whereIn("province", $regionRel->pluck("provinceCode")->toArray())
                                            ->pluck("id")
                                            ->toArray();

                        $query = function ($query) use ($shopIds) {
                            return $query->whereIn("shopId", $shopIds);
                        };
                    }
                    break;
                case HomeService::REGION_SELECTION_TYPE_2:
                    $shopIds = ShopModel::query()->where("province", $regionValue)->pluck("id")->toArray();
                    if (!empty($shopIds)) {
                        $query = function ($query) use ($shopIds) {
                            return $query->whereIn("shopId", $shopIds);
                        };
                    }
                    break;
                case HomeService::REGION_SELECTION_TYPE_3:
                    $shopIds = ShopModel::query()->where("city", $regionValue)->pluck("id")->toArray();
                    if (!empty($shopIds)) {
                        $query = function ($query) use ($shopIds) {
                            return $query->whereIn("shopId", $shopIds);
                        };
                    }
                    break;
                case HomeService::REGION_SELECTION_TYPE_4:
                    $provinceCodes = [];
                    $warRegionRow  = OpenShopRegionManageModel::query()
                                                              ->with([
                                                                  "regionMappingRel" => function ($query) {
                                                                      $query->with([
                                                                          "organizationManageRel" => function ($query) {
                                                                              $query->with("regionRel");
                                                                          }
                                                                      ]);
                                                                  }
                                                              ])->where("name", $region)->first();

                    $warRegionRow->regionMappingRel->each(
                        function (OpenShopRegionManageMappingModel $manageMappingModel) use (&$provinceCodes) {
                            $provinceCodes = array_merge(
                                $provinceCodes,
                                $manageMappingModel->organizationManageRel->regionRel->pluck("provinceCode")->toArray()
                            );
                        });

                    if (!empty($provinceCodes)) {
                        $shopIds = ShopModel::query()
                                            ->whereIn("province", $provinceCodes)
                                            ->pluck("id")
                                            ->toArray();

                        $query = function ($query) use ($shopIds) {
                            return $query->whereIn("shopId", $shopIds);
                        };
                    }
                    break;
                case HomeService::REGION_SELECTION_TYPE_0:
                default:
                    $query = null;
                    break;
            }
        }

        return self::query()->when($query, function ($subQuery) use ($query) {
            return $subQuery->where($query);
        });
    }
}
